package Concurrent;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description：
 * Author: zhangc
 * Date：2017/9/29 20:59
 */
public class SemaphoreTest {

    private static Semaphore semaphore = new Semaphore(5);
    private static ExecutorService service = Executors.newFixedThreadPool(10);
    public static AtomicInteger integer = new AtomicInteger(0);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            service.execute(new SemaphoreR(semaphore));
        }
    }

}

class SemaphoreR implements Runnable {

    private Semaphore semaphore;

    public SemaphoreR(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        while (true) {
            try {
                semaphore.acquire();
                int num = new Random().nextInt(5) * 1000;
                System.out.println(SemaphoreTest.integer.incrementAndGet());
                Thread.sleep(num);
                System.out.println(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                SemaphoreTest.integer.decrementAndGet();
                semaphore.release();
            }
        }
    }
}
